from Bilibili_Data import Data
from flask import Flask, request, render_template
import time
import webbrowser

app = Flask(__name__, template_folder='templates', static_folder='static', static_url_path='/static')
data = Data()

# 用户mid
mid = ''

@app.route('/')
def index():
    global mid
    mid = '35716872'
    if request.args.get("mid"):
        mid = request.args.get("mid")
    # 用户数据
    try:
        user_info = data.get_user_info(mid)['data']
    except:
        return "你输入的mid有误或服务器故障。"
    user_data = {}
    user_data['name'] = user_info['name']
    user_data['sex'] = user_info['sex']
    user_data['sign'] = user_info['sign']
    user_data['birthday'] = user_info['birthday']
    user_data['mid'] = user_info['mid']
    user_data['level'] = user_info['level']
    user_data['vip'] = user_info['vip']['label']['text']
    user_data['total'] = user_info['total']
    # 用户视频数据
    video_list = data.get_video_list(mid)
    user_video_data = {'view':0, 'coin':0, 'like':0, 'danmaku':0, 'favorite':0, 'share':0, 'reply':0}
    for i in range(len(video_list)):
        video_info = data.get_video_info(video_list[i]['bvid'])['data']['stat']
        user_video_data['view'] += int(video_info['view'])
        user_video_data['coin'] += int(video_info['coin'])
        user_video_data['like'] += int(video_info['like'])
        user_video_data['danmaku'] += int(video_info['danmaku'])
        user_video_data['favorite'] += int(video_info['favorite'])
        user_video_data['share'] += int(video_info['share'])
        user_video_data['reply'] += int(video_info['reply'])
    
    return render_template('index.html', user_data=user_data, user_video_data=user_video_data)

@app.route('/get_video_data')
def get_video_data():
    video_list = data.get_video_list(mid)
    for i in range(len(video_list)):
        video_info = data.get_video_info(video_list[i]['bvid'])['data']
        pubdate = time.localtime(int(video_info['pubdate']))
        video_list[i]['pubdate'] = time.strftime("%Y-%m-%d %H:%M:%S", pubdate)
        
        video_info = video_info['stat']
        video_list[i]['like'] = video_info['like']
        video_list[i]['coin'] = video_info['coin']
        video_list[i]['favorite'] = video_info['favorite']
        video_list[i]['share'] = video_info['share']
        video_list[i]['danmaku'] = video_info['danmaku']
        video_list[i]['reply'] = video_info['reply']
        time.sleep(0.3)
        
    return {
        "code": 0,
        "msg": "",
        "count": 1000,
        "data": video_list
    }

if __name__ == '__main__':
    url = 'http://127.0.0.1:8080'
    webbrowser.open_new(url)
    app.run(host='0.0.0.0', port=8080, debug=False)
